package com.yousu.dashijixm.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * 需要添加依赖
 * <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
 * <dependency>
 * <groupId>com.squareup.okhttp3</groupId>
 * <artifactId>okhttp</artifactId>
 * <version>4.12.0</version>
 * </dependency>
 */
@Component
public class Sample {


    private static final long READ_TIMEOUT = 60000;
    //写入超时为60s
    private static final long WRITE_TIMEOUT = 60000;
    //连接超时为60s
    private static final long CONNECT_TIMEOUT = 60000;



    public static final String API_KEY = "EqCzDZOnBgPzWNKsKUY8yxX0";
    public static final String SECRET_KEY = "izZm2bhzD7cOnQdIjRmt6DqUqI9H8NjP";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient()
            .newBuilder()
            //设置等待时间
            .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
            .build();

    public String diaoChat(String text) throws JSONException, IOException {

        System.out.println(text);
        MediaType mediaType = MediaType.parse("application/json");

        RequestBody body = RequestBody.create(mediaType,
                "{\"messages\":[{\"role\":\"user\",\"content\":\"" + text + "\"}]}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token="
                        + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        //response.body().string()只能调用一次，第二次为空。因为response.body().string()所包含的资源往往很大 ，当客户端接收到数据之后，okhttp的缓冲区就会自动释放资源！！
        String responseStr = response.body().string();

        // 将 JSON 字符串解析为 JSONObject 对象
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(responseStr);
        // 从 JSONObject 中获取数据
        String result = jsonObject.getString("result");

        return result;
//        String regex = "\"result\":\"(.*?)\"";
//        // 创建 Pattern 对象
//        Pattern pattern = Pattern.compile(regex);
//        // 创建 Matcher 对象
//        Matcher matcher = pattern.matcher(responseStr);
//        // 查找匹配项
//        if (matcher.find()) {
//            // 输出匹配到的 result 的内容
//            return matcher.group(1);
//        } else {
//            return "没有找到匹配项";
//        }

    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}